﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security;
using System.Security.Cryptography;

namespace Undercover.Model
{
    class Security
    {
        /// <summary>
        /// used for encrypt and decrypt algorithm
        /// </summary>
        const string KEY = "000000";
        const string SALT = "Salt-Undercover";


        /// <summary>
        /// encrypt or decrypt a file
        /// </summary>
        /// <param name="isEncrypt">true:encrypt  false:decrypt</param>
        /// <param name="strInFileName">input file name</param>
        /// <param name="strOutFileName">ouput file name</param>
        /// <param name="strPassWord"></param>
        /// <param name="strSalt"></param>
        /// <returns></returns>
        public static Error_Code EncryptOrDecryptFile(bool isEncrypt, string strInFileName, string strOutFileName, string strPassWord = KEY, string strSalt = SALT)
        {            
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(strInFileName))
                {
                    return Error_Code.Err_FileNotExit;
                }

                try
                {
                    Error_Code res = Error_Code.Err_Success;
                    using (IsolatedStorageFileStream fsInput = store.OpenFile(strInFileName, FileMode.Open))
                    using (IsolatedStorageFileStream fsOutput = store.OpenFile(strOutFileName, FileMode.OpenOrCreate))
                    {
                        string strEncryted = "";

                        using (StreamReader sr = new StreamReader(fsInput))
                        {
                            string strRaw = sr.ReadToEnd();
                            res = isEncrypt ? EncryptString(strRaw, ref strEncryted, strPassWord, strSalt) : DecryptString(strRaw, ref strEncryted, strPassWord, strSalt);
                        }

                        using (StreamWriter sw = new StreamWriter(fsOutput))
                        {
                            sw.Write(strEncryted);
                        }
                    }
                    return res;
                }
                catch
                {
                    return Error_Code.Err_Unknown;
                }
            }
        }


        /// <summary>
        /// encrypt a string
        /// </summary>
        /// <param name="strIn"></param>
        /// <param name="strOut"></param>
        /// <param name="strKey"></param>
        /// <param name="strSalt"></param>
        /// <returns></returns>
        public static Error_Code EncryptString(string strIn, ref string strOut, string strKey = KEY, string strSalt = SALT)
        {
            try
            {
                using (var aes = new AesManaged())
                {
                    Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(strKey, Encoding.UTF8.GetBytes(strSalt));
                    aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
                    aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);

                    using (var memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
                        {
                            //byte[] data = Encoding.UTF8.GetBytes(strIn);
                            //cryptoStream.Write(data, 0, data.Length);
                            //cryptoStream.FlushFinalBlock();
                            using (StreamWriter streamWriter = new StreamWriter(cryptoStream, Encoding.UTF8))
                            {
                                streamWriter.Write(strIn);
                            }
                            strOut = Convert.ToBase64String(memoryStream.ToArray());
                        }
                    }
                }
                return Error_Code.Err_Success;
            }
            catch
            {
                return Error_Code.Err_Unknown;
            }
        }


        /// <summary>
        /// decrypt a string
        /// </summary>
        /// <param name="strIn"></param>
        /// <param name="strOut"></param>
        /// <param name="strKey"></param>
        /// <param name="strSalt"></param>
        /// <returns></returns>
        public static Error_Code DecryptString(string strIn, ref string strOut, string strKey = KEY, string strSalt = SALT)
        {
            try
            {
                using (var aes = new AesManaged())
                {
                    Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(strKey, Encoding.UTF8.GetBytes(strSalt));
                    aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
                    aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);

                    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(strIn)))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read))
                        {
                            using (StreamReader streamReader = new StreamReader(cryptoStream, Encoding.Unicode))
                            {
                                strOut = streamReader.ReadToEnd();
                            }
                        }
                    }
                }
                return Error_Code.Err_Success;
            }
            catch
            {
                return Error_Code.Err_Unknown;
            }
        }


        /// <summary>
        /// return value
        /// </summary>
        public enum Error_Code
        {
            Err_Success = 0,
            Err_FileNotExit,
            Err_Unknown
        }
    }
}
